<template>
  <div class="goods_new">
    <van-nav-bar title="积分商城" left-arrow @click-left="goback"/>
    <dir style="color:#fff;height: 100px;background-size: cover;margin:0;display: flex;padding-left:20px;align-items: center;" :style="{backgroundImage:`url(${bannerimg})`}">
      可用余额：{{jifen}}
    </dir>
    <van-list v-model="loading"
              :finished="finished"
              :immediate-check="false"
              finished-text="没有更多了"
              @load="getNewtList">
      <van-checkbox-group class="card-goods" v-model="checkedGoods">
        <div v-for="(item, i) in list" :key="i">
          <van-row gutter="10" class="juzhong" style="background: #fff;padding: 15px 0;margin:5px 0;">
            <van-col span="2">
              <van-checkbox :name="item.id" v-model="item.id"></van-checkbox>
            </van-col>
            <van-col span="5">
              <img :src="item.picUrl" style="width: 100%; max-height: 150px;" />
            </van-col>
            <van-col span="10">
                <div style="width: 100%;font-size:14px;color:#333;"> {{ item.name }}</div>
                <div style="width: 100%;font-size:12px;color:#ccc;"> ￥{{ item.point }}</div>
                
            </van-col>
            <van-col span="7">
              <div> <van-stepper v-model="item.number" disableInput/></div>
            </van-col>
            <div>
            </div>
          </van-row>
        </div>
      </van-checkbox-group>
    </van-list>
    <van-submit-bar
      style="bottom: 50px"
      :price="totalPrice"
      :disabled="!list.length"
      buttonText="兑换"
      :loading="isSubmit"
      @submit="pintSubmit"
    >
      <span style="margin-left: 10px;">选中（{{this.checkedGoods.length}}）</span>
    </van-submit-bar>
  </div>
</template>

<script>
import { preExchange, pointList, userGetBalance } from '@/api/api';
import { Checkbox, CheckboxGroup, Toast, Card, NavBar, List, Row, Col, Stepper, SubmitBar } from 'vant';
import scrollFixed from '@/mixin/scroll-fixed';
import { setLocalStorage } from '@/utils/local-storage';
import _ from 'lodash';

export default {
  mixins: [scrollFixed],

  data() {
    return {
      bannerimg: require('@/assets/images/integral-banner.jpg'),
      list: [],
      checkedGoods: [],
      jifen: 0,
      page: 1,
      limit: 10,
      isSubmit: false,
      loading: false,
      finished: false
    };
  },

  computed: {
    totalPrice() {
      console.log()
      return this.list.reduce(
        (total, item) =>
          total +
          (this.checkedGoods.indexOf(item.id) !== -1
            ? item.point * item.number * 100
            : 0),
        0
      );
    }
  },

  created() {
    this.init();
  },

  methods: {
    init() {
      this.page = 0;
      this.list = [];
      this.getBalance();
      this.getNewtList();
    },
    getNewtList() {
      this.page++;
      pointList({
        page: this.page,
        limit: this.limit
      }).then(res => {
        this.list.push(...res.data.data.list);
        this.checkedGoods = this.getCheckedList(this.list);
        console.log(this.list)
        this.loading = false;
        this.finished = res.data.data.page >= res.data.data.pages;
      });
    },
    getBalance () {
      userGetBalance().then(res => {
        this.jifen = res.data.data
        console.log(res)
      })
    },
    getCheckedList(goods) {
      let result = [];
      _.each(goods, v => {
        if (v.checked) {
          result.push(v.id);
        }
      });
      return result;
    },
    itemClick(id) {
      this.$router.push(`/items/detail/${id}`);
    },
    pintSubmit () {
      this.isSubmit = true;
      console.log(this.checkedGoods.length)
      if (this.checkedGoods.length < 1) {
        Toast('请选择购物车');
        this.isSubmit = false;
        return false 
      }
      if (this.totalPrice/100 > this.jifen) {
        Toast('您的积分不足');
        this.isSubmit = false;
        return false
      }
      let checklist = []
      this.list.forEach((item, index) => {
        if (this.checkedGoods.indexOf(item.id) !== -1) {
          checklist.push({id: item.id, number: item.number})
        }
      })
      
      console.log(this.totalPrice/100, 'this.totalPrice')
      preExchange({strObj: checklist}).then(res => {
        console.log(res.data.data)
        let obj = JSON.stringify(checklist);
        if (res.data.errno === 0) {
          setLocalStorage({AddressId: 0,orderTotalPoint: res.data.data.orderTotalPoint, intdata: obj});
          this.$router.push('/integral/checkout');
        } else {
          this.isSubmit = false;
          Toast(res.data.errmsg)
        }
      })
      
      
    },
    goback() {
      this.$router.go(-1);
    }
  },

  components: {
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Stepper.name]: Stepper,
    [SubmitBar.name]: SubmitBar,
    [List.name]: List,
    [Row.name]: Row,
    [Col.name]: Col,
    [Card.name]: Card,
    [NavBar.name]: NavBar,
    Toast
  }
};
</script>

<style lang="scss" scoped>
.juzhong {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>